<template>
  <div class="home-container">
    <!-- 将Header组件移到这里 -->
    <el-header class="custom-header">
      <div class="header-content">
        <div class="logo">
          <el-icon><Document /></el-icon>
          <span>AI文本智能改进系统</span>
        </div>
        <div class="user-info">
          <el-dropdown v-if="isLoggedIn" @command="handleCommand">
            <span class="user-name">
              <el-icon><User /></el-icon>
              {{ userName }}
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button v-else type="primary" @click="showLogin">
            <el-icon><User /></el-icon>
            登录
          </el-button>
        </div>
      </div>
    </el-header>

    <!-- 登录相关弹窗 -->
    <LoginDialog v-model="loginDialogVisible" @register="showRegister" @forgot="showForgot" />
    <RegisterDialog v-model="registerDialogVisible" />
    <ForgotPasswordDialog v-model="forgotDialogVisible" />

    <div class="main-content">
      <!-- 欢迎区域 -->
      <div class="welcome-section">
        <el-card class="welcome-card">
          <div class="welcome-content">
            <h1>AI文本智能改进系统</h1>
            <p>上传您的论文，智能检测AI生成内容，并提供改写建议</p>
          </div>
        </el-card>
      </div>

      <!-- 上传区域 -->
      <div class="upload-section">
        <el-card class="upload-card">
          <template #header>
            <div class="card-header">
              <span><el-icon><Upload /></el-icon> 论文上传</span>
            </div>
          </template>
          <el-upload
            class="upload-demo"
            drag
            :action="uploadUrl"
            :headers="uploadHeaders"
            :data="uploadData"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :multiple="true"
            accept=".pdf,.txt"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持单篇或批量上传PDF/TXT格式论文，单文件不超过50MB
              </div>
            </template>
          </el-upload>
        </el-card>
      </div>

      <!-- 论文列表 -->
      <div class="paper-list-section">
        <div v-if="paperList.length === 0" class="empty-state">
          <el-empty description="暂无论文，请先上传" />
        </div>
        
        <el-card v-for="paper in paperList" :key="paper.id" class="paper-card">
          <template #header>
            <div class="card-header">
              <div class="paper-title">
                <el-icon><Document /></el-icon>
                <span>{{ paper.title }}</span>
              </div>
              <div class="paper-actions">
                <el-button type="primary" :icon="Search" @click="handleDetect(paper.id)">
                  开始检测
                </el-button>
                <el-button type="danger" :icon="Delete" @click="handleDelete(paper.id)">
                  删除
                </el-button>
              </div>
            </div>
          </template>
          
          <div class="paper-info">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="上传时间">
                {{ formatTime(paper.createTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="段落数量">
                {{ paper.totalParagraphs }}
              </el-descriptions-item>
              <el-descriptions-item label="文件大小">
                {{ formatFileSize(paper.fileSize) }}
              </el-descriptions-item>
              <el-descriptions-item label="检测状态">
                <el-tag :type="getStatusType(paper.status)">
                  {{ paper.status }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 检测结果 -->
          <div v-if="paper.detectionResults" class="detection-results">
            <el-divider>检测结果</el-divider>
            
            <!-- 可视化统计 -->
            <div class="statistics">
              <div class="stat-item">
                <div class="stat-value">{{ paper.avgProbability }}%</div>
                <div class="stat-label">平均AI概率</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ paper.highRiskCount }}</div>
                <div class="stat-label">高风险段落</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ paper.totalParagraphs }}</div>
                <div class="stat-label">总段落数</div>
              </div>
            </div>

            <!-- 段落列表 -->
            <div class="paragraph-list">
              <div
                v-for="(paragraph, index) in paper.paragraphs"
                :key="index"
                class="paragraph-item"
                :class="getRiskClass(paragraph.aiProbability)"
                @click="handleParagraphClick(paragraph, paper.id)"
              >
                <div class="paragraph-header">
                  <span class="paragraph-number">段落 {{ index + 1 }}</span>
                  <el-tag :type="getRiskTagType(paragraph.aiProbability)" size="small">
                    {{ getRiskLevel(paragraph.aiProbability) }}
                  </el-tag>
                </div>
                <div class="paragraph-content">{{ paragraph.content }}</div>
                <div class="paragraph-footer">
                  <span class="paragraph-probability">
                    AI生成概率: <strong>{{ paragraph.aiProbability }}%</strong>
                  </span>
                  <el-button type="primary" size="small" @click.stop="handleRewriteSingle(paragraph, paper.id)">
                    智改此段
                  </el-button>
                </div>
              </div>
            </div>
            
            <!-- 操作按钮 -->
            <div class="action-buttons">
              <el-button type="success" :icon="Edit" @click="handleSmartRewrite(paper.id)">
                整篇智改
              </el-button>
              <el-button type="info" :icon="Download" @click="handleExportReport(paper.id)">
                导出PDF报告
              </el-button>
              <el-button type="warning" :icon="View" @click="handleViewChart(paper.id)">
                查看统计图表
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 改写弹窗 -->
    <el-dialog v-model="rewriteDialogVisible" title="智能改写" width="80%" :close-on-click-modal="false">
      <div class="rewrite-comparison">
        <div class="original-text">
          <h3>原文</h3>
          <div class="text-content">{{ selectedParagraph.content }}</div>
          <div class="probability-info">
            <el-tag :type="getRiskTagType(selectedParagraph.aiProbability)">
              AI概率: {{ selectedParagraph.aiProbability }}%
            </el-tag>
          </div>
        </div>
        <div class="rewritten-text">
          <h3>改写后</h3>
          <el-input
            v-model="rewrittenContent"
            type="textarea"
            :rows="10"
            placeholder="点击'生成改写'自动生成，或手动编辑改写内容..."
          />
          <div class="probability-info">
            <el-tag v-if="rewrittenProbability > 0" :type="getRiskTagType(rewrittenProbability)">
              AI概率: {{ rewrittenProbability }}%
            </el-tag>
            <el-tag v-if="probabilityDiff > 0" type="success">
              降低: {{ probabilityDiff }}%
            </el-tag>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="rewriteDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="rewriting" @click="generateRewrite">
          生成改写
        </el-button>
        <el-button type="success" :disabled="!rewrittenContent" @click="confirmRewrite">
          确认改写
        </el-button>
      </template>
    </el-dialog>

    <!-- 图表弹窗 -->
    <el-dialog v-model="chartDialogVisible" title="检测报告可视化" width="90%">
      <VisualReport v-if="chartDialogVisible" :paper-id="selectedPaperId" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Upload, Document, Search, Delete, Edit, Download, View,
  UploadFilled, User, ArrowDown, SwitchButton
} from '@element-plus/icons-vue'
import LoginDialog from '@/views/Login.vue'
import RegisterDialog from '@/views/Register.vue'
import ForgotPasswordDialog from '@/views/ForgotPassword.vue'
import VisualReport from '@/components/VisualReport.vue'
import { 
  uploadPaper, detectPaper, rewriteParagraph, getPaperList, 
  exportReport, deletePaper 
} from '@/api'

const userStore = useUserStore()

const paperList = ref([])
const rewriteDialogVisible = ref(false)
const chartDialogVisible = ref(false)
const loginDialogVisible = ref(false)
const registerDialogVisible = ref(false)
const forgotDialogVisible = ref(false)
const selectedParagraph = ref({})
const selectedPaperId = ref(null)
const rewrittenContent = ref('')
const rewrittenProbability = ref(0)
const rewriting = ref(false)

const isLoggedIn = computed(() => userStore.isLoggedIn)
const userName = computed(() => userStore.userName)

const uploadUrl = computed(() => `${import.meta.env.VITE_API_BASE_URL}/api/paper/upload`)
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${userStore.token}`
}))
const uploadData = computed(() => ({
  userId: userStore.userId
}))

const showLogin = () => {
  loginDialogVisible.value = true
}

const showRegister = () => {
  loginDialogVisible.value = false
  registerDialogVisible.value = true
}

const showForgot = () => {
  loginDialogVisible.value = false
  forgotDialogVisible.value = true
}

const handleCommand = (command) => {
  if (command === 'logout') {
    userStore.logout()
    ElMessage.success('已退出登录')
  }
}

const getRiskClass = (probability) => {
  if (probability <= 30) return 'low-risk'
  if (probability <= 60) return 'medium-risk'
  if (probability <= 90) return 'high-risk'
  return 'very-high-risk'
}

const getRiskTagType = (probability) => {
  if (probability <= 30) return 'success'
  if (probability <= 60) return 'warning'
  if (probability <= 90) return 'danger'
  return 'danger'
}

const getRiskLevel = (probability) => {
  if (probability <= 30) return '低风险'
  if (probability <= 60) return '中风险'
  if (probability <= 90) return '高风险'
  return '极高风险'
}

const getStatusType = (status) => {
  const statusMap = {
    '待检测': 'info',
    '检测中': 'warning',
    '已完成': 'success',
    '失败': 'danger'
  }
  return statusMap[status] || 'info'
}

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

const beforeUpload = (file) => {
  const isValidType = file.type === 'application/pdf' || file.type === 'text/plain'
  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isValidType) {
    ElMessage.error('只能上传PDF或TXT格式的文件!')
    return false
  }
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过50MB!')
    return false
  }
  return true
}

const handleUploadSuccess = (response) => {
  ElMessage.success('上传成功')
  loadPaperList()
}

const handleUploadError = () => {
  ElMessage.error('上传失败，请重试')
}

const handleDetect = async (paperId) => {
  try {
    ElMessage.info('开始检测，请稍候...')
    const result = await detectPaper(paperId)
    ElMessage.success('检测完成')
    loadPaperList()
  } catch (error) {
    ElMessage.error('检测失败: ' + error.message)
  }
}

const handleDelete = async (paperId) => {
  try {
    await ElMessageBox.confirm('确定要删除这篇论文吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deletePaper(paperId)
    ElMessage.success('删除成功')
    loadPaperList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleParagraphClick = (paragraph, paperId) => {
  selectedParagraph.value = { ...paragraph, paperId }
  rewrittenContent.value = ''
  rewrittenProbability.value = 0
  rewriteDialogVisible.value = true
}

const handleRewriteSingle = (paragraph, paperId) => {
  handleParagraphClick(paragraph, paperId)
}

const generateRewrite = async () => {
  rewriting.value = true
  try {
    const result = await rewriteParagraph(
      selectedParagraph.value.paperId,
      selectedParagraph.value.id
    )
    rewrittenContent.value = result.rewrittenContent
    rewrittenProbability.value = result.newProbability
    ElMessage.success('改写生成成功')
  } catch (error) {
    ElMessage.error('改写生成失败: ' + error.message)
  } finally {
    rewriting.value = false
  }
}

const confirmRewrite = async () => {
  try {
    await rewriteParagraph(
      selectedParagraph.value.paperId,
      selectedParagraph.value.id,
      rewrittenContent.value
    )
    ElMessage.success('改写成功')
    rewriteDialogVisible.value = false
    loadPaperList()
  } catch (error) {
    ElMessage.error('改写失败: ' + error.message)
  }
}

const handleSmartRewrite = async (paperId) => {
  try {
    await ElMessageBox.confirm('确定要对整篇论文进行智能改写吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    ElMessage.info('正在进行智能改写，请稍候...')
    await rewriteParagraph(paperId, -1)
    ElMessage.success('改写完成')
    loadPaperList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('改写失败: ' + error.message)
    }
  }
}

const handleExportReport = async (paperId) => {
  try {
    const blob = await exportReport(paperId)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `论文检测报告_${paperId}.pdf`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('报告导出成功')
  } catch (error) {
    ElMessage.error('报告导出失败')
  }
}

const handleViewChart = (paperId) => {
  selectedPaperId.value = paperId
  chartDialogVisible.value = true
}

const loadPaperList = async () => {
  try {
    const papers = await getPaperList(userStore.userId)
    paperList.value = papers
  } catch (error) {
    ElMessage.error('加载论文列表失败')
  }
}

const probabilityDiff = computed(() => {
  return selectedParagraph.value.aiProbability - rewrittenProbability.value
})

onMounted(() => {
  if (userStore.isLoggedIn) {
    loadPaperList()
  }
})
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.custom-header {
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 24px;
  font-weight: bold;
  color: #667eea;
}

.user-name {
  cursor: pointer;
  font-size: 16px;
  color: #333;
  display: flex;
  align-items: center;
  gap: 5px;
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.welcome-card {
  margin-bottom: 20px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.welcome-content {
  text-align: center;
  padding: 30px;
}

.welcome-content h1 {
  font-size: 36px;
  margin-bottom: 10px;
}

.welcome-content p {
  font-size: 18px;
  opacity: 0.9;
}

.upload-card, .paper-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.paper-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: bold;
}

.paper-info {
  margin-bottom: 20px;
}

.statistics {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #667eea;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.paragraph-list {
  max-height: 600px;
  overflow-y: auto;
}

.paragraph-item {
  padding: 15px;
  margin: 10px 0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.paragraph-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.low-risk {
  background-color: #e8f5e9;
  border-left: 4px solid #4caf50;
}

.medium-risk {
  background-color: #fff9c4;
  border-left: 4px solid #ffeb3b;
}

.high-risk {
  background-color: #ffe0b2;
  border-left: 4px solid #ff9800;
}

.very-high-risk {
  background-color: #ffcdd2;
  border-left: 4px solid #f44336;
}

.paragraph-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.paragraph-number {
  font-weight: bold;
  color: #303133;
}

.paragraph-content {
  line-height: 1.8;
  color: #606266;
  margin-bottom: 10px;
}

.paragraph-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.paragraph-probability {
  font-weight: bold;
}

.action-buttons {
  margin-top: 20px;
  text-align: center;
}

.empty-state {
  padding: 100px 0;
}

.rewrite-comparison {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.rewrite-comparison h3 {
  margin-bottom: 10px;
  color: #303133;
}

.text-content {
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
  line-height: 1.8;
  min-height: 150px;
}

.probability-info {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}
</style>